<?php

namespace app\console\controller;

use think\Url;
use think\Cache;
use think\Loader;
use think\Request;
use think\Controller;
use app\console\model\AuthRule as AuthRuleModel;
use app\common\trilateral\Classify as ClassifyAlias;

class AuthRule extends Controller
{

    protected $beforeActionList = [
        'clearCache' => ['only'],
    ];

    /**
    * 规则列表
    */
    public function index()
    {


        return $this->fetch('index', [
            'mate_title' => '规则列表',
            'data'       => ClassifyAlias::dimension(Cache::get('rule'))
        ]);
    }


    /**
    * 规则添加
    */
    public function create()
    {

        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();

            // 验证
            $validate = Loader::validate('AuthRule');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = (new AuthRuleModel())->allowField(true)->save($data);

            if ($dispose) {
                win('操作成功', Url::build('AuthRule/index'));
            }

            fail('操作失败');

        }

        return $this->fetch('create', [
            "mate_title" => '用户规则添加',
            'rule_list' => ClassifyAlias::dimension(Cache::get('rule'))

        ]);

    }


    /*
     * 规则操作
     */
    public function destroy($id)
    {

        if (AuthRuleModel::amputate($id)) {
            win('操作成功', Url::build('console/AuthRule/index'));
        }

        fail('操作失败');

    }


    /*
      * 规则全部操作
    */
    public function destroyAll($id)
    {

        if (AuthRuleModel::amputateAll($id)) {
            win('操作成功', Url::build('console/AuthRule/index'));
        }

        fail('操作失败');

    }


    /*
     * 用户操作
     */
    public function update($id)
    {

        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();

            // 验证
            $validate = Loader::validate('AuthRule');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = (new AuthRuleModel())->allowField(true)->save($data, ['id' => $id]);

            if ($dispose !== false) {
                win('操作成功', Url::build('AuthRule/index'));
            }

            fail('操作失败');

        }

        $item = AuthRuleModel::get($id);
        //halt(ClassifyAlias::dimension(Cache::get('rule')));
        return $this->fetch('create', [
            "mate_title" => '规则操作',
            'item'       => $item,
            'rule_list' => ClassifyAlias::dimension(Cache::get('rule'))

        ]);
    }

    /*
     * 清除缓存
     */
    protected function clearCache()
    {
        Cache::rm('rule');
    }
}